/***********************************************************************
 * Module:  RecordFile.java
 * Author:  wy
 * Purpose: Defines the Class RecordFile
 ***********************************************************************/

package wxdb.record;

import wxdb.tx.Transaction;

/*
 * just a bunch of pages 
 * this class is used to iterate these pages in a single db file
 */
public class RecordBundle {
   private TableInfo ti;
   private RecordPage rp;
   private int dbid;
   private int currentPageListId;			//number of the page in pageList: 0,1,2...
   
   
   /** @param ti
    */
   public RecordBundle(TableInfo ti) {			
      this.ti = ti;
 
      if(ti.isEmpty()){			//first page number
    	  appendPage();
    	  currentPageListId = 0;
      }
      moveTo(0);
   }
   
   public TableInfo getTableInfo(){
	   return ti;
   }
   
   
   /** @param pid
    */
   private void moveTo(int num) {
      this.currentPageListId = num;
      rp = new RecordPage(ti.getTruePid(num), ti);
   }
   
   private void appendPage() {
	  RecordFormatter rf = new RecordFormatter(ti); 
      int pid = Transaction.append(dbid, rf);
      if(pid < 0){
    	  System.out.println("failed to allocate new page");
    	  System.exit(-1);
      }
      else
    	  ti.addPage(-1, pid);
   }
   
   private boolean isLastPage() {
      return (ti.getPageNum()-1 == currentPageListId);
   }
   
   public void first() {
      moveTo(0);
   }
   
   public boolean next() {
	  while(true){
	      if(rp.next()){
	    	  return true;
	      }
	      else if(isLastPage())
	    	  return false;
	      moveTo(currentPageListId+1);
	  }
   }
   
   /** @param fldName
    */
   public int getInt(String fldName) {
      return rp.getInt(fldName);
   }
   
   /** @param fldName
    */
   public String getString(String fldName) {
      return rp.getString(fldName);
   }
   
   /** @param fldName 
    * @param ival
    */
   public void setInt(String fldName, int ival) {
      rp.setInt(fldName, ival);
   }
   
   /** @param fldName 
    * @param sval
    */
   public void setString(String fldName, String sval) {
      rp.setString(fldName, sval);
   }
   
   public void delete() {
      rp.delete();
   }
   
   public void insert() {
      while(!rp.insert()){
    	  if(isLastPage())
    		  appendPage();
    	  moveTo(currentPageListId+1);
      }
   }
   
   /** @param rid
    */
   public void moveToRid(RID rid) {
	  int pageListNum = ti.getPageListId(rid.getPid());
      moveTo(pageListNum);
      rp.moveTo(rid.getSlotNum());
   }
   
   public RID getCurrentRid() {
      return new RID(ti.getTruePid(currentPageListId), rp.getCurrentlot());
   }

}